# include "Chest.h"

# include "Renderer.h"

# include "Map.h"

Chest::Chest()
{

}

Chest::~Chest()
{

}

void Chest::setPosition( const Ogre::Vector3& position)
{
	mySceneNode->setPosition( position);
}

void Chest::init( Renderer* renderer, Map* map)
{
	myRenderer = renderer;
	myMap = map;	
}

void Chest::load( const std::string& name, unsigned int indice)
{
	myType = CHEST;

	lua_State* stateTmp = lua_open();
	luaL_openlibs( stateTmp);
	luaL_dofile( stateTmp, LUA_OBJECT_ACTION);
	lua_settop( stateTmp, 0);
	unsigned int indiceTmp = 1;

	lua_getglobal( stateTmp, name.c_str());

	std::ostringstream streamTmp;
	streamTmp << name << indice;

	lua_pushnumber( stateTmp, indiceTmp++);
	lua_gettable( stateTmp, -2);
	myEntity = myRenderer->createEntity( streamTmp.str(), lua_tostring( stateTmp, -1));
	lua_pop( stateTmp, 1);
	
	streamTmp << "Node";
	
	mySceneNode = myRenderer->createSceneNode( streamTmp.str());
	mySceneNode->attachObject( myEntity);
	myEntity->setQueryFlags( ACTION_FLAG);

	lua_pushnumber( stateTmp, indiceTmp++);
	lua_gettable( stateTmp, -2);
	mySceneNode->yaw( Ogre::Degree( lua_tonumber( stateTmp, -1)));
	lua_pop( stateTmp, 1);
	
	lua_pushnumber( stateTmp, indiceTmp++);
	lua_gettable( stateTmp, -2);
	unsigned int numberTmp = lua_tonumber( stateTmp, -1);
	lua_pop( stateTmp, 1);

	for ( unsigned int i = 0; i < numberTmp; i++ )
	{
		lua_pushnumber( stateTmp, indiceTmp++);
		lua_gettable( stateTmp, -2);
		myObjects.push_back( new std::string( lua_tostring( stateTmp, -1)));
		lua_pop( stateTmp, 1);
	}

	lua_pop( stateTmp, 1);
	lua_close( stateTmp);
}

void Chest::open()
{
	myEntity->setQueryFlags( WALL_FLAG);

	while ( myObjects.size() )
	{
		myMap->addObjectPickUp( *myObjects.back(), mySceneNode->getPosition());
		delete myObjects.back();
		myObjects.pop_back();
	}
}